from django_redis import get_redis_connection
from django.conf import settings
from django.contrib.auth import login
from django.shortcuts import render
from django import http
# Create your views here.
from QQLoginTool.QQtool import OAuthQQ
from django.views import View
import json,re
import logging

from oauth.models import OAuthQQUser
from oauth.utils import get_access_token, server_access_token
from users.models import User

logger = logging.getLogger('django')
class QQURLView(View):
    def get(self,request):
        next = request.GET.get('next')
        oauth = OAuthQQ(client_id=settings.QQ_CLIENT_ID,
                        client_secret=settings.QQ_CLIENT_SECRET,
                        redirect_uri=settings.QQ_REDIRECT_URI,
                        state=next)
        login_url = oauth.get_qq_url()
        return http.JsonResponse({
            'code':0,
            'errmsg':'ok',
            'login_url':login_url
        })
class QQUserView(View):
    '''用户登录回调处理'''
    def get(self,request):
        code = request.GET.get('code')
        if not code:
            return http.JsonResponse({
                'code':400,
                'errmsg':'缺少code参数',
            })
        oauth = OAuthQQ(
            client_id=settings.QQ_CLIENT_ID,
            client_secret=settings.QQ_CLIENT_SECRET,
            redirect_uri=settings.QQ_REDIRECT_URI
        )
        # Oauth认证2.0
        try:
            access_token = oauth.get_access_token(code)
            openid = oauth.get_open_id(access_token)
        except Exception as e:
            logger.error(e)
            return http.JsonResponse({
                'code':400,
                'errmsg':'oauth2.0认证失败，获取QQ信息失败',
            })
        try:
            oauth_qq = OAuthQQUser.objects.get(openid=openid)
        except OAuthQQUser.DoesNotExist:
            access_token = get_access_token(openid)
            return http.JsonResponse({
                'code':300,
                'errmsg':'ok',
                'access_token':access_token
            })
        else:
            user = oauth_qq.user
            login(request,user)
            response = http.JsonResponse({
                'code':0,
                'errmsg':'ok'
            })
            response.set_cookie(
                'username',
                user.username,
                max_age=3600*24*14,
            )
            return response



    def post(self,request):
        '''美多商城用户绑定'''
        dict = json.loads(request.body.decode())
        mobile = dict.get('mobile')
        password = dict.get('password')
        sms_code_clien = dict.get('sms_code')
        access_token = dict.get('access_token')
        if not all([mobile,password,sms_code_clien]):
            return http.JsonResponse({
                'code':400,
                'errmsg':'缺少参数'
            })
        if not re.match(r'^1[3-9]\d{9}$',mobile):
            return http.JsonResponse({
                'code':400,
                'errmsg':'moblie格式有误'
            })
            # 判断密码是否合格
        if not re.match(r'^[0-9A-Za-z]{8,20}$', password):
            return http.JsonResponse({'code': 400,
                                  'errmsg': '请输入8-20位的密码'})
        redis_conn = get_redis_connection('verify_code')
        sms_code_server = redis_conn.get('sms_%s' % mobile)
        if not sms_code_server:
            return http.JsonResponse({
                'code':400,
                'errmsg':'验证码过期'
            })
        if sms_code_server.decode() != sms_code_clien:
            return http.JsonResponse({
                'code':400,
                'errrmsg':'验证码错误'
            })
        openid = server_access_token(access_token)
        if not openid:
            return http.JsonResponse({'code': 400,
                                      'errmsg': '缺少openid'})
        try:
            user = User.objects.get(mobile=mobile)
        except Exception as e:
            user = User.objects.create_user(username=mobile,
                                            password=password,
                                            mobile=mobile)
        else:
        # 如果用户存在，检查用户密码
            if not user.check_password(password):
                return http.JsonResponse({'code': 400,
                                          'errmsg': '输入的密码不正确'})
        try:
            OAuthQQUser.objects.create(openid=openid,
                                       user=user)
        except Exception as e:
            return http.JsonResponse({'code': 400,
                                      'errmsg': '往数据库添加数据出错'})
        login(request, user)
        response = http.JsonResponse({'code': 0,
                                      'errmsg': 'ok'})

        # 8.登录时用户名写入到 cookie，有效期14天
        response.set_cookie('username',
                            user.username,
                            max_age=3600 * 24 * 14)

        # 9.响应
        return response